package com.tanhua.server.service;

import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.DateUtils;
import com.tanhua.dubbo.api.PeachApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.Peach;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.PeachVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;


@Service
public class PeachblossomService {
    @Autowired
    private OssTemplate ossTemplate;
    @DubboReference
    private PeachApi peachApi;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;

    public PeachVo peachReceive() throws ParseException {
        String redisKey = DateUtils.getRanmdomDaysAgo(0)+"_Peach_Chance";
        PeachVo vo= new PeachVo();
        //判断接收语音的次数
        String remainingTimes = redisTemplate.opsForValue().get(redisKey);
        Integer PeachChance = Integer.valueOf(remainingTimes);
        if (PeachChance>0){
            Peach peach = peachApi.getRandomOne();
            Long posterId = peach.getPosterId();
            String soundUrl = peach.getSoundUrl();
            UserInfo userInfo = userInfoApi.findById(posterId);
            vo.setSoundUrl(soundUrl);
            vo.setAge(userInfo.getAge());
            vo.setAvatar(userInfo.getAvatar());
            vo.setGender(userInfo.getGender());
            vo.setId(Math.toIntExact(posterId));
            vo.setNickname(userInfo.getNickname());
            vo.setRemainingTimes(PeachChance);
            redisTemplate.opsForValue().decrement(redisKey,1);
            peachApi.update(peach);
        }
        return vo;
    }

        public void peachPost (MultipartFile soundFile) throws IOException {
            String soundUrl = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
            Long posterId = UserHolder.getUserId();
            peachApi.save(soundUrl, posterId);

        }
    }

